package com.glodon.paas.databag.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.glodon.paas.databag.api.bean.DatabagDto;
import com.glodon.paas.databag.service.DatabagService;
import com.glodon.paas.exception.PaasServerExceptionFactory;

@Controller
@RequestMapping("/public")
public class PublicController {
    public final Logger logger = LoggerFactory.getLogger(PublicController.class);
    // 如过当前Databag是公开的数据包，则将databag Id放入到session中，此为session中的Key.
    public final static String SESSION_PUBLIC_DATABAG = "publicDatabag";

    @Autowired
    private DatabagService databagService;

    @RequestMapping(value="/{token}", method = RequestMethod.GET)
    public ModelAndView publicPage(@PathVariable("token") String token, @RequestParam("type") String type,
            HttpSession session) {
        DatabagDto dto = databagService.findByToken(token);
        if (dto != null) {// 将当前公开的databag Id放入到session中
            session.setAttribute(SESSION_PUBLIC_DATABAG, dto.getId());
            String viewType = databagService.getDatabagType(type);
            if ("rvt".equals(viewType) || "dwg".equals(viewType)) {
                viewType = "dwgrvt";
            } else if ("doc".equals(viewType)) {
                viewType = "office";
            }
            return new ModelAndView(viewType);
        } else {
            throw PaasServerExceptionFactory.accessForbidden("token [" + token + "] is not published.", null);
    	}
    }
}
